package com.relax.applicationContext;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;
import org.springframework.beans.BeansException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class TomcatAnnotationConfigApplicationContext  extends AnnotationConfigApplicationContext {
    @Override
    protected void onRefresh(){
        /**
         * springboot启动时候创建tomcat的代码是在
         * org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer(org.springframework.boot.web.servlet.ServletContextInitializer...)
         */
        Tomcat tomcat = new Tomcat();

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(8081);

        StandardEngine engine = new StandardEngine();
        engine.setDefaultHost("localhost");

        StandardHost host = new StandardHost();
        host.setName("localhost");

        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);// todo springboot 一样

        service.setContainer(engine);// todo springboot 一样
        service.addConnector(connector);

        //关键：向tomcat容器添加dispatcherServlet的servlet，DispatcherServlet需要很具接受的请求去匹配某个controller中的对应方法
        tomcat.addServlet(contextPath, "dispatcher",new DispatcherServlet());  //SpringMVC中的DispatcherServlet，其中还有所有controller和注解，applicationContext就是所有Controller的所有的bean
        context.addServletMappingDecoded("/*","dispatcher");  //接收的所有请求交给dispatcher处理

        tomcat.addServlet(contextPath, "hello", new HelloServlet());
        context.addServletMappingDecoded("/hello","hello");  //接收的所有请求交给dispatcher处理

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }

    }



    public TomcatAnnotationConfigApplicationContext(Class<?>... componentClasses) {
        super(componentClasses);
    }
}
